package com.uinnova.product.eam.service.cj.service.impl;

import com.uinnova.product.eam.model.cj.domain.CJResource;
import com.uinnova.product.eam.model.cj.domain.ChapterResource;
import com.uinnova.product.eam.model.cj.vo.ContextFileVo;
import com.uinnova.product.eam.service.cj.dao.CJResourceDao;
import com.uinnova.product.eam.service.cj.dao.ChapterResourceDao;
import com.uinnova.product.eam.service.cj.service.CJResourceDaoService;
import com.uinnova.product.eam.service.exception.BusinessException;
import com.uino.bean.permission.base.SysUser;
import com.uino.dao.util.ESUtil;
import com.uino.util.rsm.RsmUtils;
import com.uino.util.sys.SysUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

@Service
@Slf4j
public class CJResourceDaoServiceImpl implements CJResourceDaoService {

    @Autowired
    private CJResourceDao cjResourceDao;
    @Autowired
    private ChapterResourceDao chapterResourceDao;

    @Autowired
    private RsmUtils rsmUtils;

    @Value("${local.resource.space}")
    private String localPath;

    @Value("${http.resource.space}")
    private String httpPath;


    @Value("${obs.rsm.url.prefix:/tarsier-eam/rsm}")
    private String rsmUrlPrefix;

    @Value("${obs.use}")
    private boolean obsUseFlag;


    @Override
    public List<CJResource> upload(MultipartFile[] files, SysUser currentUserInfo) {
        List<CJResource> resources = new ArrayList<>(files.length);
        String userName = currentUserInfo.getLoginCode();
        Stream.of(files).forEach(file -> resources.add(saveFile(file, userName)));
        return resources;
    }

    @Override
    public List<ChapterResource> uploadChapterFile(MultipartFile[] files, SysUser currentUserInfo, Long templateId, Long chapterId) {
        List<ChapterResource> resources = new ArrayList<>(files.length);
        String userName = currentUserInfo.getLoginCode();
        Stream.of(files).forEach(file -> resources.add(saveChapterFile(file, userName,templateId,chapterId)));
        return resources;
    }

    @Override
    public ContextFileVo uploadContextFile(MultipartFile file) {
        return saveContextFile(file);
    }

    @Override
    public void ossTest(MultipartFile file, String objectKey) {
        log.info("进入阿里云文件上传服务");
        Long dateTimeFolder = ESUtil.getNumberDate();
        File destFolder = new File(localPath+"/"+dateTimeFolder);
        if(!destFolder.exists()){
            destFolder.mkdirs();
        }
        String docName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String destFileName = ESUtil.getUUID() + "." + fileType;
        File destFile = new File(destFolder, destFileName);
        String resPath = "/" + dateTimeFolder + "/" + destFileName;
        try {
            file.transferTo(new File(destFile.getCanonicalPath()));
            rsmUtils.uploadRsmFromFile(new File(destFile.getCanonicalPath()));
            CJResource resource = new CJResource();
            resource.setCreateTime(ESUtil.getNumberDateTime());
            resource.setModifyTime(resource.getCreateTime());
            resource.setId(ESUtil.getUUID());
            resource.setName(docName);
            resource.setOperator(SysUtil.getCurrentUserInfo().getLoginCode());
            resource.setResType(fileType);
            resource.setResPath(resPath);
            cjResourceDao.saveOrUpdate(resource);
            System.out.println(resource.toString());
        } catch (Exception e) {
            throw new BusinessException(e.getMessage());
        }
    }

    private ContextFileVo saveContextFile(MultipartFile file) {
        Long dateTimeFolder = ESUtil.getNumberDate();
        File destFolder = new File(localPath+"/"+dateTimeFolder);
        if(!destFolder.exists()){
            destFolder.mkdirs();
        }
        try {
            String docName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
            String destFileName = ESUtil.getUUID() + "." + fileType;
            File destFile = new File(destFolder, destFileName);
            String resPath = "/" + dateTimeFolder + "/" + destFileName;
            file.transferTo(new File(destFile.getCanonicalPath()));

            rsmUtils.uploadRsmFromFile(new File(destFile.getCanonicalPath()));

            ContextFileVo contextFileVo = new ContextFileVo();
            contextFileVo.setCreateTime(ESUtil.getNumberDateTime());
            contextFileVo.setModifyTime(contextFileVo.getCreateTime());
            contextFileVo.setResourceName(docName);
            contextFileVo.setOperator( SysUtil.getCurrentUserInfo().getLoginCode());
            contextFileVo.setResourceType(fileType);
            contextFileVo.setResourcePath(httpPath + resPath);
            return contextFileVo;
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }

    @Override
    public Boolean checkUploadFileCount(Long templateId, Long chapterId) {
        ChapterResource resource = new ChapterResource();
        resource.setTemplateId(templateId);
        resource.setChapterId(chapterId);
        List<ChapterResource> chapterResources = chapterResourceDao.getListByCdt(resource);
        if (CollectionUtils.isEmpty(chapterResources)) {
            return true;
        }
        return chapterResources.size() <= 5;
    }

    @Override
    public void deleteChapterFile(Long id) {
        chapterResourceDao.deleteById(id);
    }

    @Override
    public List<ChapterResource> getPlanResource(Long templateId,Long chapterTemplateId) {
        ChapterResource chapterResource = new ChapterResource();
        chapterResource.setTemplateId(templateId);
        chapterResource.setChapterId(chapterTemplateId);
        List<SortBuilder<?>> sorts = new ArrayList<>();
        FieldSortBuilder modifyTimeSortBuilder = SortBuilders.fieldSort("modifyTime").order(SortOrder.ASC);
        sorts.add(modifyTimeSortBuilder);
        return chapterResourceDao.getSortListByCdt(chapterResource, sorts);
    }

    private ChapterResource saveChapterFile(MultipartFile file, String operator,Long templateId,Long chapterId){
        Long dateTimeFolder = ESUtil.getNumberDate();
        File destFolder = new File(localPath+"/"+dateTimeFolder);
        if(!destFolder.exists()){
            destFolder.mkdirs();
        }
        String docName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String destFileName = ESUtil.getUUID() + "." + fileType;
        File destFile = new File(destFolder, destFileName);
        String resPath = "/" + dateTimeFolder + "/" + destFileName;
        try {

            file.transferTo(new File(destFile.getCanonicalPath()));
            rsmUtils.uploadRsmFromFile(new File(destFile.getCanonicalPath()));

            ChapterResource resource = new ChapterResource();
            resource.setCreateTime(ESUtil.getNumberDateTime());
            resource.setModifyTime(resource.getCreateTime());
            resource.setId(ESUtil.getUUID());
            resource.setResourceName(docName);
            resource.setOperator(operator);
            resource.setResourceType(fileType);
            resource.setResourcePath(resPath);
            resource.setTemplateId(templateId);
            resource.setChapterId(chapterId);
            chapterResourceDao.saveOrUpdate(resource);

            // 保存半路径，返回全路径
            resource.setResourcePath(httpPath + resPath);
            return resource;
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }

    private CJResource saveFile(MultipartFile file, String operator){
        Long dateTimeFolder = ESUtil.getNumberDate();
        File destFolder = new File(localPath+"/"+dateTimeFolder);
        if(!destFolder.exists()){
            destFolder.mkdirs();
        }
        String docName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
        String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        String destFileName = ESUtil.getUUID() + "." + fileType;
        File destFile = new File(destFolder, destFileName);
        String resPath = "/" + dateTimeFolder + "/" + destFileName;
        try {

            file.transferTo(new File(destFile.getCanonicalPath()));
            rsmUtils.uploadRsmFromFile(new File(destFile.getCanonicalPath()));

            CJResource resource = new CJResource();
            resource.setCreateTime(ESUtil.getNumberDateTime());
            resource.setModifyTime(resource.getCreateTime());
            resource.setId(ESUtil.getUUID());
            resource.setName(docName);
            resource.setOperator(operator);
            resource.setResType(fileType);
            resource.setResPath(resPath);
            cjResourceDao.saveOrUpdate(resource);
            return resource;
        } catch (IOException e) {
            throw new BusinessException(e.getMessage());
        }
    }
}
